package com.jianguozh.difs.support.api.framework;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jianguozh.difs.common.bean.R;
import com.jianguozh.difs.framework.annotation.WriteLog;
import com.jianguozh.difs.framework.base.BaseController;
import com.jianguozh.difs.framework.utils.SecurityUtils;
import com.jianguozh.difs.support.api.framework.dto.PwdModifyDto;
import com.jianguozh.difs.support.service.sys.entity.User;
import com.jianguozh.difs.support.service.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 安全相关接口
 *
 * @author hanrs
 * @email 4076130@qq.com
 * @since 2022/6/20 9:39
 */
@RestController
public class SecurityController extends BaseController {

    @Autowired
    IUserService userService;

    /**
     * 修改密码
     *
     * @param pwdModifyDto
     * @return
     */
    @PutMapping("/pwd")
    @WriteLog(value = "修改密码")
    public R<Boolean> modifyPwd(@Validated @RequestBody PwdModifyDto pwdModifyDto) {
        String userId = SecurityUtils.getLoginUser().getId();
        Boolean result = false;
        User user = userService.getById(userId);
        if (!SecurityUtils.matchesPassword(pwdModifyDto.getOldPassword(), user.getPassword())) {
            return failed("原密码输入有误.");
        }
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(User::getPassword, SecurityUtils.encryptPassword(pwdModifyDto.getPassword()));
        if (pwdModifyDto.getFirst()) {
            updateWrapper.set(User::getPwdInited, true);
        }
        updateWrapper.eq(User::getId, userId);
        result = userService.update(updateWrapper);
        return success(result);
    }

}
